<template>
  <view class="" style="width: 100vw;height: 100vh;background-color: #000;">
    <video style="width: 100vw;height:calc(100vh - 500rpx);" object-fit="cover"></video>
    <!--相机水印-->
    <view>
      <!--签到打卡水印-->
      <WatermarkSign v-if="templeteId == 1" :waterInfo="waterInfo" :userInfo="userInfo"></WatermarkSign>
    </view>
    <view style="position: relative;">
      <view v-if="templeteId == 2" class="menu-header">
        <view class="m-h-left" @tap="syncPictureShow = true"><text style="color: #fff;">同步：绿港工程</text></view>
        <view class="m-h-right" @tap="myTeam"><text style="color: #fff;">我的团队</text></view>
      </view>
      <view class="menu-middle">
        <!--返回键-->
        <view class="menu-item">
          <image class="menu-back" @tap="goBack" src="@/static/watermark-camera/backWhite.png"></image>
        </view>
        <!--快门键-->
        <view class="menu-item">
          <image class="menu-snapshot" @tap="handlePhotographClick" src="@/static/watermark-camera/kuaimenWhite.png">
          </image>
        </view>
        <!--水印模板-->
        <view class="menu-item">
          <image class="menu-flip" @tap="flip" src="@/static/watermark-camera/flipWhite.png"></image>
        </view>
      </view>
    </view>

  </view>

</template>
<script>
let _this = null;
import { useChatStore, useGroupStore, useSocketStore, useUserStore } from '@/pinia-store/user';
import { mapStores } from 'pinia';
import WatermarkSign from "@/components/watermarkCamera/templete/watermarkSign.vue";
// #ifdef H5
import AMapLoader from "@amap/amap-jsapi-loader"
window._AMapSecurityConfig = {
  securityJsCode: "6a3b0ae034d75c523abf64e1a334791e" // 设置你的安全密钥
};
// #endif
export default {
  components: {
    WatermarkSign,
  },
  data () {
    return {
      userInfo: {},
      imageUrl: "",
      waterInfo: {
        projName: '请输入内容...',//水印 工程名称
        constructionContent: '请输入内容...',//水印 施工内容
        address: '地址',//水印中地址部分
        lngLat: [],
        hm: '',//时分
        ymd: '',//年月日
        ymdhms: '',//年月日时分秒
        weatherDesc: '',//天气
        time: '',//水印中时间部分
        alpha: '',//方位角
        consUnit: '江苏绿港数字农业科技有限公司',//施工单位
      },
      timer: null, //定时器
      // 媒体流，用于关闭摄像头
      mediaStreamTrack: null,
      popupshow: false,
      templeteId: 1,//水印模板id
      syncPictureShow: false,
      facingMode: 'environment',
      source:'', // 来源
      id:'', // 审批单id
      itemId:'', // 起码组件还是止码组件
      apply_id:'', // 起码组件还是止码组件
      component_id:'', // 起码组件还是止码组件
      qrToken:'',
    };
  },
  computed: {
    ...mapStores(useChatStore, useGroupStore, useUserStore, useSocketStore),
  },
  watch: {

  },
  onReady () {
    let date = new Date();
    this.waterInfo.time = this.dateFormat("YYYY-mm-dd HH:MM:SS", date);
    this.waterInfo.ymdhms = this.dateFormat("YYYYmmddHHMMSS", date);
    this.waterInfo.hm = this.dateFormat("HH:MM", date);
    this.waterInfo.ymd = this.dateFormat("YYYY.mm.dd", date);
  },
  onShow () {
    this.getAddress();
    clearInterval(this.timer)
    this.timer = null;
    // 每隔10秒刷新地址和时间
    this.timer = setInterval(() => {
      this.getAddress();
      let date = new Date();
      this.waterInfo.time = this.dateFormat("YYYY-mm-dd HH:MM:SS", date);
      this.waterInfo.ymdhms = this.dateFormat("YYYYmmddHHMMSS", date);
      this.waterInfo.hm = this.dateFormat("HH:MM", date);
      this.waterInfo.ymd = this.dateFormat("YYYY.mm.dd", date);
    }, 10000);
    this.invokingCamera(this.facingMode);
  },
  onLoad (e) {
    uni.showLoading({ title: '加载中...' });
    this.source = e?.source || ''
    this.id = e?.id || ''
    this.itemId = e?.itemId || ''
    this.apply_id = e?.apply_id || ''
    this.component_id = e?.component_id || ''
    this.qrToken = e?.qrToken || ''
    _this = this;
    if (e.templeteId != undefined) {
      //console.log("templeteId====", e.templeteId)
      _this.templeteId = e.templeteId;
    }
    //初始化相机
    // this.invokingCamera(_this.facingMode);

    // 获取APP用户信息
    _this.userInfo = _this.userStore.user;
  },
  onUnload () {
    clearInterval(this.timer);
    this.timer = null;
    this.handlePhotographCloseClick();
    this.stopCompass();
  },
  methods: {
    invokingCamera (facingMode) {
      const self = this;
      // 注意本例需要在HTTPS协议网站中运行，新版本Chrome中getUserMedia接口在http下不再支持。

      // 老的浏览器可能根本没有实现 mediaDevices，所以我们可以先设置一个空的对象
      if (navigator.mediaDevices === undefined) {
        navigator.mediaDevices = {};
      }

      // 一些浏览器部分支持 mediaDevices。我们不能直接给对象设置 getUserMedia
      // 因为这样可能会覆盖已有的属性。这里我们只会在没有getUserMedia属性的时候添加它。
      if (navigator.mediaDevices.getUserMedia === undefined) {
        navigator.mediaDevices.getUserMedia = function (constraints) {
          // 首先，如果有getUserMedia的话，就获得它
          const getUserMedia =
            navigator.getUserMedia ||
            navigator.webkitGetUserMedia ||
            navigator.mozGetUserMedia;

          // 一些浏览器根本没实现它 - 那么就返回一个error到promise的reject来保持一个统一的接口
          if (!getUserMedia) {
            return Promise.reject(
              new Error("getUserMedia is not implemented in this browser")
            );
          }

          // 否则，为老的navigator.getUserMedia方法包裹一个Promise
          return new Promise(function (resolve, reject) {
            getUserMedia.call(navigator, constraints, resolve, reject);
          });
        };
      }

      uni.getSystemInfo({
        success: function (res) {
          const constraints = {
            audio: false,
            video: {
              // 前置摄像头user 后置摄像头environment
              facingMode: facingMode,
              mirror: false,
              // 手机端相当于高
              width: Math.max(res.windowWidth, res.windowHeight) - 120,
              // 手机端相当于宽
              height: Math.min(res.windowWidth, res.windowHeight),
            },
          };

          navigator.mediaDevices.getUserMedia(constraints).then(function (stream) {
            self.mediaStreamTrack = stream;

            const video = document.querySelector("video");
            // 旧的浏览器可能没有srcObject
            if ("srcObject" in video) {
              video.srcObject = stream;
            } else {
              // 防止在新的浏览器里使用它，应为它已经不再支持了
              video.src = window.URL.createObjectURL(stream);
            }
            video.onloadedmetadata = function (e) {
              video.play();
            };
          }).catch(function (err) {
            console.log(err.name + ": " + err.message);
          });
        },
      });
    },
    // 获取地址
    getAddress () {
      AMapLoader.load({
        key: "c9c069d05cb4075e3e24aefea6f77b85", // 高德key
        version: "2.0",
        plugins: ["AMap.Geocoder", "AMap.Geolocation"],
      }).then((AMap) => {
        const geocoder = new AMap.Geocoder();
        const geolocation = new AMap.Geolocation({
          enableHighAccuracy: true,
          timeout: 10000
        });
        geolocation.getCurrentPosition((status, res) => {
          //console.log("res=getCurrentPosition=",res);
          if (status === 'complete') {
            _this.waterInfo.lngLat = [res.position.lng, res.position.lat];
            geocoder.getAddress(_this.waterInfo.lngLat, (geoStatus, result) => {
              //console.log("123====", result)
              if (geoStatus === 'complete' && result.info === 'OK') {
                let location = result.regeocode.formattedAddress;
                if (_this.templeteId == 2 && location.length > 22) {
                  location = location.substring(0, 21) + '...';
                  //获取天气
                  _this.doAsyncRequest2(result.regeocode.addressComponent.adcode);
                  _this.startCompass();
                }
                _this.waterInfo.address = location;
              }
            });
          }

           uni.hideLoading();
        });

      }).catch((e) => {
        console.error("高德地图加载失败:", e);
        uni.hideLoading();
      })
    },
    async doAsyncRequest2 (cityCode) {
      var res = await this.getWeather(cityCode);
      if (res.data.count > 0) {
        let resArr = res.data.lives;
        _this.waterInfo.weatherDesc = resArr[0].weather + ' ' +
          resArr[0].temperature + '°C ' + resArr[0].winddirection + '风' + resArr[0].windpower + '级 ' +
          '空气湿度' + resArr[0].humidity + '%';
      }
    },
    //高德api 获取天气
    getWeather (adcode) {
      let key = '9a99fd7f598782ffd1a05d6dd67757ff';
      return new Promise((resolve, reject) => {
        uni.request({
          url: 'https://restapi.amap.com/v3/weather/weatherInfo?key=' + key + '&city=' + adcode, // 请求的URL
          method: 'GET', // 请求方式，默认为GET
          success: function (res) {
            console.log('请求成功:', res);
            resolve(res);
          },
          fail: function (err) {
            console.error('请求失败:', err); // 请求失败后的回调函数
            reject(err);
          }
        });
      });
    },
    //反转
    flip () {
      let facingMode = _this.facingMode == 'environment' ? 'user' : 'environment';
      //console.log("flip====", facingMode)
      this.invokingCamera(facingMode);
      _this.facingMode = facingMode;
      const video = document.querySelector("video");
      console.log("facingMode==", facingMode)
      if (facingMode == 'user') {
        video.style.cssText = "width: 100vw;height:calc(100vh - 500rpx);transform: rotateY(180deg);-webkit-transform: rotateY(180deg);-moz-transform: rotateY(180deg);";
      } else {
        video.style.cssText = "width: 100vw;height:calc(100vh - 500rpx);transform: rotateY(0deg);-webkit-transform: rotateY(0deg);-moz-transform: rotateY(0deg);";
      }
    },
    //罗盘 方位角
    startCompass () {
      console.log('startCompass==1===');
      uni.onCompassChange((res) => {
        console.log('startCompass==2===', res);
        if (res.direction) {
          console.log('startCompass==3===', res);
          _this.getAlpha(res.direction);
        }
      });
      uni.startCompass();
    },
    stopCompass () {
      uni.stopCompass();
    },
    getAlpha (direction) {
      if (direction >= 0 && direction < 90) {
        _this.waterInfo.alpha = '东北' + Math.round(direction) + '°';
      } else if (direction >= 90 && direction < 180) {
        _this.waterInfo.alpha = '东南' + Math.round(direction) + '°';
      } else if (direction >= 180 && direction < 270) {
        _this.waterInfo.alpha = '西南' + Math.round(direction) + '°';
      } else if (direction >= 270 && direction < 360) {
        _this.waterInfo.alpha = '西北' + Math.round(direction) + '°';
      }
    },
    handlePhotographCloseClick () {
      if (this.mediaStreamTrack) {
        // 关闭摄像头
        this.mediaStreamTrack.getTracks().forEach(function (track) {
          track.stop();
        });
        this.mediaStreamTrack = null;
      }
    },
    handlePhotographClick () {
      const self = this;
      const canvas = document.createElement("canvas");
      const ctx = canvas.getContext("2d");
      const video = document.querySelector("video");
      canvas.width = Math.min(video.videoWidth, video.videoHeight);
      canvas.height = Math.max(video.videoWidth, video.videoHeight);
      if (_this.facingMode == 'environment') {
        ctx.translate(canvas.width, 0);
        ctx.scale(-1, 1);
      }
      ctx.drawImage(video, 0, 0, canvas.width, canvas.height);

      // ****** 镜像处理 ******
      function getPixel (imageData, row, column) {
        const uint8ClampedArray = imageData.data;
        const width = imageData.width;
        const height = imageData.height;
        const pixel = [];
        for (let i = 0; i < 4; i++) {
          pixel.push(uint8ClampedArray[row * width * 4 + column * 4 + i]);
        }
        return pixel;
      }

      function setPixel (imageData, row, column, pixel) {
        const uint8ClampedArray = imageData.data;
        const width = imageData.width;
        const height = imageData.height;
        for (let i = 0; i < 4; i++) {
          uint8ClampedArray[row * width * 4 + column * 4 + i] = pixel[i];
        }
      }

      const mirrorImageData = ctx.createImageData(canvas.width, canvas.height);
      const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
      for (let h = 0; h < canvas.height; h++) {
        for (let w = 0; w < canvas.width; w++) {
          const pixel = getPixel(imageData, h, canvas.width - w - 1);
          setPixel(mirrorImageData, h, w, pixel);
        }
      }
      ctx.putImageData(mirrorImageData, 0, 0);
      // ****** 镜像处理 ******

      self.$nextTick(() => {
        const base64 = canvas.toDataURL("image/jpeg");
        self.imageUrl = base64;
        //console.log("self.imageUrl====", self.imageUrl)
        self.handlePhotographCloseClick();
        self.snapshot();
      });
    },
    snapshot () {
      if (_this.templeteId == 99) {
        //无水印
        //保存相册
        _this.saveImageToAlbum();
      } else if (_this.templeteId == 1) {
        //跳转
        let info = {
          path: _this.imageUrl,
          info: {
            workerName: _this.userInfo.worker_name,
            dateHm: _this.waterInfo.hm,
            dateYmd: _this.waterInfo.ymd,
            dateYmdhms: _this.waterInfo.ymdhms,
            address: _this.waterInfo.address,
          }
        };
        uni.navigateTo({
          url: `/pages/watermarkCamera/canvas?source=${this.source}&id=${this.id}&itemId=${this.itemId}&apply_id=${this.apply_id}&component_id=${this.component_id}&qrToken=${this.qrToken}`,
          success: function (res) {
            res.eventChannel.emit('snapshotInfo', { snapshot: info });
          }
        });
      } else if (_this.templeteId == 2) {
        if (_this.waterInfo.projName == '请输入内容...') {
          uni.$u.toast('请完善水印信息');
          return;
        }
        if (_this.waterInfo.constructionContent == '请输入内容...') {
          uni.$u.toast('请完善水印信息');
          return;
        }
        //跳转
        let info = {
          path: _this.imageUrl,
          info: {
            projId: _this.waterInfo.projId,
            projName: _this.waterInfo.projName,
            content: _this.waterInfo.constructionContent,
            address: _this.waterInfo.address,
            time: _this.waterInfo.time,
            weather: _this.waterInfo.weatherDesc,
            alpha: _this.waterInfo.alpha,
            consUnit: _this.waterInfo.consUnit,
            lngLat: JSON.stringify(_this.waterInfo.lngLat),
          }
        };
        uni.navigateTo({
          url: "/pages/watermarkCamera/myTeam",
          success: function (res) {
            res.eventChannel.emit('snapshotInfo', { snapshot: info });
          }
        });
      }
    },
    //保存相册
    saveImageToAlbum () {

      var image = _this.imageUrl.replace("image/png", "image/octet-stream"); // 转换为blob以触发下载
      var link = document.createElement('a');
      link.download = 'image-' + _this.waterInfo.ymdhms + '.png';
      link.href = image;
      link.click();
    },
    //选择水印模板
    selectMark () {
      _this.popupshow = true;
    },
    close () {
      this.popupshow = false;
    },
    handleClose (params) {
      this.close();
    },
    //格式化时间
    dateFormat (fmt, date) {
      let ret;
      const opt = {
        "Y+": date.getFullYear().toString(), // 年
        "m+": (date.getMonth() + 1).toString(), // 月
        "d+": date.getDate().toString(), // 日
        "H+": date.getHours().toString(), // 时
        "M+": date.getMinutes().toString(), // 分
        "S+": date.getSeconds().toString() // 秒
        // 有其他格式化字符需求可以继续添加，必须转化成字符串
      };
      for (let k in opt) {
        ret = new RegExp("(" + k + ")").exec(fmt);
        if (ret) {
          fmt = fmt.replace(ret[1], (ret[1].length == 1) ? (opt[k]) : (opt[k].padStart(ret[1].length, "0")))
        };
      };
      return fmt;
    },
    closeSyncPicture () {
      this.syncPictureShow = false;
    },
    myTeam () {
      uni.navigateTo({
        url: "/pages/watermarkCamera/myTeam",
        success: function (res) {
          //标识直接跳转，与拍照后跳转区分
          res.eventChannel.emit('jumpType', 'direct');
        }
      })
    },
    //处理水印信息
    handleWaterInfo (params) {
      //console.log("handleWaterInfo=======", params);
      if (params) {
        _this.waterInfo.projId = params.projId;
        _this.waterInfo.projName = params.projName;
        _this.waterInfo.constructionContent = params.content;
        _this.waterInfo.consUnit = params.unitName;
      }
    },
    //返回
    goBack () {
      let delta = this.source == 'h5homeIndex' ? 2 : 1
      // 关闭摄像头
      this.handlePhotographCloseClick();

      // 停止罗盘监听
      this.stopCompass();
      uni.navigateBack({ delta: delta });
    },
  },
};
</script>

<style scoped>
video {
  transform: rotateY(0deg);
  -webkit-transform: rotateY(0deg);
  /* Safari 和 Chrome */
  -moz-transform: rotateY(0deg);
}

/deep/ .uni-video-bar {
  display: none;
}

/deep/ .uni-video-cover {
  display: none;
}

.menu-header {
  position: absolute;
  top: 0;
  display: flex;

  .m-h-left {
    width: 375rpx;
    display: flex;
    justify-content: center;
    align-items: center;
    background-color: #262626;
    height: 100rpx;
    border-right: 1px solid #909399;
  }

  .m-h-right {
    width: 375rpx;
    display: flex;
    justify-content: center;
    align-items: center;
    background-color: #262626;
    height: 100rpx;
  }
}

.menu-flip {
  width: 60rpx;
  height: 55rpx;
}

.menu-middle {
  display: flex;
  //flex-direction: row;
  justify-content: space-around;
  align-items: center;
  height: 500rpx;

  .menu-back {
    width: 50rpx;
    height: 50rpx;
  }

  .menu-snapshot {
    width: 128rpx;
    height: 128rpx;
  }

  .menu-watermark {
    width: 64rpx;
    height: 64rpx;
    border-radius: 10rpx;
  }
}

.popup-sync {
  height: 750rpx;

  .header-title {
    padding: 20rpx;
    height: 100rpx;
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    align-items: center;
    border-bottom: 1px solid #f0f0f0;

    .header-close {
      .up-icon {
        font-size: 40rpx;
      }
    }

    .header-text {
      font-size: 35rpx;
    }
  }

  .popup-content {
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    padding: 20rpx;

    .left {
      width: 400rpx;
      display: flex;
      flex-direction: row;
      align-items: center;

      .popup-logo {
        width: 120rpx;
        height: 54rpx;
        margin-right: 10rpx;
      }
    }

    .right {
      width: 300rpx;
      text-align: right;
    }
  }

}
</style>
